﻿using System.Net.Http.Json;

namespace Away.Admin.Services.Implements;

[ServiceInject(ServiceLifetime.Scoped)]
public class ApiResourceService : IApiResourceService
{
    private readonly IApiResourceRepository _apiResourceRepository;
    private readonly IHttpClientFactory _httpClientFactory;
    public ApiResourceService(IApiResourceRepository apiResourceRepository, IHttpClientFactory httpClientFactory)
    {
        _apiResourceRepository = apiResourceRepository;
        _httpClientFactory = httpClientFactory;
    }

    public bool AddApiResource(SysApiResource model)
    {
        return _apiResourceRepository.AddApiResource(model);
    }

    public ApiResult GetApiResourcePage(ApiResourceSearch search)
    {
        return _apiResourceRepository.GetApiResourcePage(search);
    }

    public bool RemoveApiResource([Required] int[] ids)
    {
        return _apiResourceRepository.RemoveApiResource(ids);
    }

    public bool UpdateApiResource(SysApiResource model)
    {
        return _apiResourceRepository.UpdateApiResource(model);
    }

    public async Task ImportSwaggerApi(string url)
    {
        using var client = _httpClientFactory.CreateClient();
        var model = await client.GetFromJsonAsync<ApiSwaggerModel>(url);
        _apiResourceRepository.ImportApiResource(model?.ToEntities()!);
    }

    public List<ApiResourceTree> GetApiResourceTree()
    {
        var list = _apiResourceRepository.GetApiResourceList();
        var groups = list.Select(o => o.Group).Distinct().OrderBy(o => o).ToList();

        var trees = list.Select(o =>
        {
            var groupId = groups.IndexOf(o.Group) + 1;
            return new ApiResourceTree
            {
                Id = o.Id,
                ApiName = o.ApiName,
                ParentId = groupId == 0 ? 0 : 0 - groupId,
            };
        }).ToList();

        trees.AddRange(groups.Select((o, i) => new ApiResourceTree
        {
            Id = 0 - (i + 1),
            ApiName = o,
            Disabled = true
        }));

        return TreeBuilder.Build(trees);
    }
}
